package com.kcl.dfss;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.kcl.dfss.utils.AppUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ShareAppActivity extends Activity implements OnClickListener{

	protected static final String tag = "ShareAppActivity";
	
	private LinearLayout layout_share_back,bottom;
	private ImageView share_wb,share_qq,share_wx,share_pyq,share_head;
	private TextView share_username,share_time,share_mileage;
//	private TextView share_warn;
	private SharedPreferences preferences = null;
	private Bitmap bitmap = null;
	private int time = 0,mileage = 0,warn = 0;
	private PackageManager pminfo = null;
	private ProgressBar sharebar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_share_app);
		
		ShareSDK.initSDK(ShareAppActivity.this);
		
		pminfo = this.getPackageManager();
		
		layout_share_back = (LinearLayout) findViewById(R.id.layout_share_back);
		bottom = (LinearLayout) findViewById(R.id.bottom);
		share_wb = (ImageView) findViewById(R.id.share_wb);
		share_qq = (ImageView) findViewById(R.id.share_qq);
		share_wx = (ImageView) findViewById(R.id.share_wx);
		share_pyq = (ImageView) findViewById(R.id.share_pyq);
		sharebar = (ProgressBar) findViewById(R.id.sharebar);
		
		share_head = (ImageView) findViewById(R.id.share_head);
		share_username = (TextView) findViewById(R.id.share_username);
		share_time = (TextView) findViewById(R.id.share_time);
		share_mileage = (TextView) findViewById(R.id.share_mileage);
//		share_warn = (TextView) findViewById(R.id.share_warn);
		
		layout_share_back.setOnClickListener(this);
		share_wb.setOnClickListener(this);
		share_qq.setOnClickListener(this);
		share_wx.setOnClickListener(this);
		share_pyq.setOnClickListener(this);
		
		preferences = getSharedPreferences("shared_login", 0);
		//设置用户名
		String username = preferences.getString("usernick","");
		share_username.setText(username);
		//设置头像
		final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 1){
					share_head.setImageBitmap(bitmap);
				}
			}
		};
		final String url = preferences.getString("userhead", null);
		if(AppUtils.isNetworkAvailable(ShareAppActivity.this)){
			if(url!=null){
				new Thread(new Runnable() {
					@Override
					public void run() {
						bitmap = AppUtils.getHttpBitmap(url);
						if(bitmap!=null){
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);								
						}
					}
				}).start();
			}	
		}
		
		//设置统计文字字体颜色
		String stime = String.format(getResources().getString(R.string.share1), time);
		int ftime = stime.indexOf(String.valueOf(time));
		int fend = ftime+String.valueOf(time).length();
		SpannableStringBuilder style1 = new SpannableStringBuilder(stime);
		style1.setSpan(new ForegroundColorSpan(Color.parseColor("#4F964B")), ftime, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		share_time.setText(style1);
		
		String smileage = String.format(getResources().getString(R.string.share2), mileage);
		int fmileage = smileage.indexOf(String.valueOf(mileage));
		int fend2 = fmileage+String.valueOf(mileage).length();
		SpannableStringBuilder style2 = new SpannableStringBuilder(smileage);
		style2.setSpan(new ForegroundColorSpan(Color.parseColor("#4B8796")), fmileage, fend2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		share_mileage.setText(style2);
		
		/*String swarn = String.format(getResources().getString(R.string.share3), warn);
		int fwarn = swarn.indexOf(String.valueOf(warn));
		int fend3 = fwarn+String.valueOf(warn).length();
		SpannableStringBuilder style3 = new SpannableStringBuilder(swarn);
		style3.setSpan(new ForegroundColorSpan(Color.parseColor("#A4AC4C")), fwarn, fend3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		share_warn.setText(style3);*/
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_share_back:
			finish();
			break;
		case R.id.share_wb:
			String result = getAppName("com.sina.weibo");
			if(result.equals("微博")){
//				sharebar.setVisibility(View.VISIBLE);
				String imagename = getDate();
				File file = new File(Environment.getExternalStorageDirectory()+imagename);
				takeScreenShot(ShareAppActivity.this, file);
				shareToSina(file);
			}else{
				Toast.makeText(ShareAppActivity.this, "未安装该应用", Toast.LENGTH_SHORT).show();				
			}
			break;
		case R.id.share_qq:
			String result2 = getAppName("com.tencent.mobileqq");
			if(result2.equals("QQ")){
//				sharebar.setVisibility(View.VISIBLE);
				String imagename = getDate();
				File file = new File(Environment.getExternalStorageDirectory()+imagename);
				takeScreenShot(ShareAppActivity.this, file);
				shareToQQ(file);
			}else{
				Toast.makeText(ShareAppActivity.this, "未安装该应用", Toast.LENGTH_SHORT).show();
			}
			/*String imagename5 = getDate();
			File file5 = new File(Environment.getExternalStorageDirectory()+imagename5);
			takeScreenShot(ShareAppActivity.this, file5);
			shareToQZone(file5);*/
			break;
		case R.id.share_wx:
			String result4 = getAppName("com.tencent.mm");
			if(result4.equals("微信")){
//				sharebar.setVisibility(View.VISIBLE);
				String imagename = getDate();
				File file = new File(Environment.getExternalStorageDirectory()+imagename);
				takeScreenShot(ShareAppActivity.this, file);
				shareToWeChat(file);
			}else{
				Toast.makeText(ShareAppActivity.this, "未安装该应用", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.share_pyq:
//			sharebar.setVisibility(View.VISIBLE);
			String result3 = getAppName("com.tencent.mm");
			if(result3.equals("微信")){
				String imagename2 = getDate();
				File file2 = new File(Environment.getExternalStorageDirectory()+imagename2);
				takeScreenShot(ShareAppActivity.this, file2);
				shareToWeChatFriend(file2);
			}else{
				Toast.makeText(ShareAppActivity.this, "未安装该应用", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}
	
	/*
	 * 截图并保存图片
	 */
	private void takeScreenShot(Activity activity,File file){
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bitmap1 = view.getDrawingCache();
		
		//获取状态栏高度
		Rect frame = new Rect();
		view.getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		
		//获取屏幕长和高
		int width = activity.getWindowManager().getDefaultDisplay().getWidth();
		int height = activity.getWindowManager().getDefaultDisplay().getHeight();
		
		//去掉标题栏
		int topheight = layout_share_back.getHeight();
		int bottomheight = bottom.getHeight();
		Bitmap bitmap2 = Bitmap.createBitmap(bitmap1, 0, statusBarHeight+topheight, width, height-statusBarHeight-topheight-bottomheight);
		view.destroyDrawingCache();
		
		try {
			FileOutputStream out = new FileOutputStream(file);
			bitmap2.compress(CompressFormat.PNG, 100, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//以当前时间作为截图保存的名字
	@SuppressLint("SimpleDateFormat")
	private String getDate(){
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		String time = format.format(date);
		return "/"+time+".png";
	}
	
	//获得指定包名的APP的名字
	private String getAppName(String packname){
		try{
			ApplicationInfo info = pminfo.getApplicationInfo(packname, 0);	
			return info.loadLabel(pminfo).toString();
		}catch(NameNotFoundException e){
			e.printStackTrace();
		}
		return "error";
	}
	
	//分享到微信朋友圈（老方法，未用SDK）
	private void shareToTimeLine(File file){
		Intent intent = new Intent();
		ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
		intent.setComponent(comp);
		intent.setAction("android.intent.action.SEND");
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		startActivity(intent);
	}
	
	//分享到新浪微博
	public void shareToSina(File file){
		ShareParams sp = new ShareParams();
		
		sp.setText("径卫视觉为您保驾护航");
		sp.setImagePath(file.toString());
		Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
		weibo.share(sp);
		/*weibo.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				Log.i(tag, "新浪微博分享不成功");
				sharebar.setVisibility(View.GONE);
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				Log.i(tag, "新浪微博分享成功");
				sharebar.setVisibility(View.GONE);
				Toast.makeText(ShareAppActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				Log.i(tag, "新浪微博分享取消");
				sharebar.setVisibility(View.GONE);
			}
		});*/
	}
	
	//分享到微信联系人
	public void shareToWeChat(File file){
		ShareParams sp = new ShareParams();
		sp.setText("径卫视觉为您保驾护航");
		sp.setImagePath(file.toString());
		Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
		weChat.share(sp);
		/*weChat.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				Log.i(tag, "微信联系人分享不成功");
				sharebar.setVisibility(View.GONE);
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				Log.i(tag, "微信联系人分享成功");
				sharebar.setVisibility(View.GONE);
				Toast.makeText(ShareAppActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				Log.i(tag, "微信联系人分享取消");
				sharebar.setVisibility(View.GONE);
			}
		});*/
	}
	
	//分享到微信朋友圈
	public void shareToWeChatFriend(File file){
		ShareParams sp = new ShareParams();
		sp.setText("径卫视觉为您保驾护航");
		sp.setImagePath(file.toString());
		Platform weChatFriend = ShareSDK.getPlatform(WechatMoments.NAME);
		weChatFriend.share(sp);
		/*weChatFriend.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				Log.i(tag, "朋友圈分享不成功");
				sharebar.setVisibility(View.GONE);
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				Log.i(tag, "朋友圈分享成功");
				sharebar.setVisibility(View.GONE);
				Toast.makeText(ShareAppActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				Log.i(tag, "朋友圈分享取消");
				sharebar.setVisibility(View.GONE);
			}
		});*/
	}
	
	public void shareToQZone(File file){
		ShareParams sp = new ShareParams();
		sp.setText("径卫视觉为您保驾护航");
		sp.setImagePath(file.toString());
		Platform qZone = ShareSDK.getPlatform(QZone.NAME);
		qZone.share(sp);
	}
	
	public void shareToQQ(File file){
		ShareParams sp = new ShareParams();
		sp.setTitle("疲劳预警");
		sp.setTitleUrl("http://www.roadefend.com");
		sp.setText("径卫视觉为您保驾护航");
		sp.setImagePath(file.toString());
		Platform qq = ShareSDK.getPlatform(QQ.NAME);
		qq.share(sp);
		qq.setPlatformActionListener(new PlatformActionListener() {
			
			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {
				Log.i(tag, "QQ分享不成功");
			}
			
			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				Log.i(tag, "QQ分享完成，可以回调");
			}
			
			@Override
			public void onCancel(Platform arg0, int arg1) {
				Log.i(tag, "QQ分享取消");
			}
		});
	}

}
